package service_book

import (
	"tools-api/src/common/db/database"
	"tools-api/src/jcj/model"
	"xorm.io/xorm"
)

// GetCurrentBook 获取当前账本
func GetCurrentBook(uuid string) model.Book {
	return model.Book{}.GetCurrent(uuid)
}

// GetBookList 我的账本列表
func GetBookList(uuid string) []model.BookResult {
	return model.Book{}.GetList(uuid)
}

// BookAddOrUpdate 新增/修改
func BookAddOrUpdate(book model.Book) (bool, string) {
	if book.Id > 0 { // 修改
		_, err := book.Update()
		if err != nil {
			return false, "修改失败"
		}
		return true, "修改成功"
	} else { // 新增
		book = book.Create()
		if book.Id == 0 {
			return false, "添加失败"
		}
		return true, "添加成功"
	}
}

// BookDelete 删除
func BookDelete(uuid string, id int64) error {
	return database.Session(database.JCJEngine.NewSession(), func(session *xorm.Session) error {
		// 删除账本
		err := model.Book{}.Delete(session, uuid, id)
		if err != nil {
			return err
		}
		// 删除该账本下的记账明细
		err = model.BookDetail{}.DeleteDetailByBook(session, uuid, id)
		return err
	})
}

// BookSetCurrent 设置当前账本
func BookSetCurrent(uuid string, id int64) error {
	return model.Book{}.BookSetCurrent(uuid, id)
}
